package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.utils.Logger;

public class MyPopupWindow extends PopupWindow {
	private Context mContext = null;
	private int width = 0;
	private int height = 0;
	private TextView mVolumeText;
	private ImageView mGreenBgs[];

	public MyPopupWindow(Context cxt) {
		mContext = cxt;
		mGreenBgs = new ImageView[5];
		initView();
	}

	private void initView() {
		View mView = null;
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mView = inflater.inflate(R.layout.popup_window_layout, null);
		mVolumeText = (TextView)mView.findViewById(R.id.popup_voice_volumn);
		((Activity) mContext).getWindowManager().getDefaultDisplay() .getHeight();
		height = ((Activity) mContext).getWindowManager().getDefaultDisplay().getHeight();
		width = ((Activity) mContext).getWindowManager().getDefaultDisplay().getWidth();
		this.setWidth((int)(width/3.5));
		this.setHeight((int)(width/3.5));
		initGreenBgs(mView);
		setContentView(mView);
	}

	public void showPopupWindow(View parent) {
		if (!this.isShowing()) {
			System.out.println("xionghy: xPos: " + (width/2 - this.getWidth()/2) + " -- getWidth: " + getWidth() + " -- width" + width);
			this.showAsDropDown(parent, width/2 - this.getWidth()/2, 50);
		}
	}

	public void setVolumeText(float v) {
		Logger.e("xionghy - setVolumeText - volume: " + v);
		mVolumeText.setText("" + v);
		setGreenBgsVisibility(v);
	}

	public void dimissPopupWindow() {
		this.dismiss();
	}

	private void initGreenBgs(View view) {
		mGreenBgs[4] = (ImageView)view.findViewById(R.id.popup_voice_greenview_1);
		mGreenBgs[3] = (ImageView)view.findViewById(R.id.popup_voice_greenview_2);
		mGreenBgs[2] = (ImageView)view.findViewById(R.id.popup_voice_greenview_3);
		mGreenBgs[1] = (ImageView)view.findViewById(R.id.popup_voice_greenview_4);
		mGreenBgs[0] = (ImageView)view.findViewById(R.id.popup_voice_greenview_5);
	}

	private void setGreenBgsVisibility(float volume) {
		if (volume < 6) {
			setViewVisibility(0);
		} else if (volume < 10) {
			setViewVisibility(1);
		} else if (volume < 15) {
			setViewVisibility(2);
		} else if (volume < 18) {
			setViewVisibility(3);
		} else {
			setViewVisibility(4);
		}
	}

	private void setViewVisibility(int id) {
		for (int i=0; i<5; i++) {
			if(i<=id) {
				mGreenBgs[i].setVisibility(View.VISIBLE);
			} else {
				mGreenBgs[i].setVisibility(View.INVISIBLE);
			}
		}
	}
}
